import sys
import vecc_lexer
import gramloader

from Lexer import *
from vm import *
from pars import *

def compileTarget(target, grammarTarget):
    automata = vecc_lexer.getVectorCAutomata()
    lexer = Lexer(automata, BufferedFileReader(target, 'stdlib.code'))
#    lexer = Lexer(automata, BufferedFileReader(target))

    g = gramloader.loadGrammar(grammarTarget)

    push_lexer = PushLexer(lexer)
    comment_strip_lexer = CommentFilterLexer(push_lexer)
    final_lexer = KeywordLexer(comment_strip_lexer, ['if', 'for', 'print', 'read', 'goto', 'label', 'while', 'return', 'operator', 'struct', 'typedef'])
    analyzer = SRAnalyzer(final_lexer, g.f, g.g)
    return analyzer.run()

def run(bytecode, silent, screenOut = True):
    vm = VM(silent, screenOut)
    return vm.run(bytecode)    

if __name__ == '__main__':

    if len(sys.argv) < 2:
        print "KCC program launcher"
        print "Usage: runProgram [-s] <target> [grammar]"
        print "       NB! grammar is grammar.py by default"
        print "       NB! -s enables silent mode"
        sys.exit(0)



    target = sys.argv[1]

    silent = False
    if '-s' in sys.argv:
        silent = True
        sys.argv.remove('-s')

    if len(sys.argv) >= 3:
        grammar = sys.argv[2]
    else:
        grammar = "grammar.py"

    bytecode = compileTarget(target, grammar)

    run(bytecode, silent)
